package com.topnav.mc.admin.controller;

import com.js.lib.annotation.ApiLogger;
import com.js.lib.result.Result;
import com.topnav.mc.admin.bean.OrgDeviceBean;
import com.topnav.mc.admin.entity.Device;
import com.topnav.mc.admin.service.IDeviceService;
import com.topnav.mc.admin.service.impl.DeviceQueryImpl;
import com.topnav.mc.admin.service.impl.DeviceTreeServiceImpl;
import com.topnav.mc.position.PositionInfo;
import com.topnav.mc.position.PositionUtil;
import com.topnav.mc.uitls.MapUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Api(value = "admin/device", tags = "设备管理")
@RestController
@CrossOrigin
@RequestMapping("admin/device")
public class DeviceTreeController {

    @Resource
    private DeviceTreeServiceImpl deviceTreeServiceImpl;
    @Resource
    private DeviceQueryImpl deviceQueryImpl;
    @Autowired
    private PositionUtil positionUtil;
    @Autowired
    private IDeviceService deviceService;



    /**
     * 带单位树型结构的设备列表
     * 给前端 Tree组件使用
     * 没有输入id参数时，查询第一层（有权限控制）
     * 有id时则查询些id的下一级
     * 有些设备下有多个通道，则此id,为单位id--设备Id,结果休是能道列表
     * */
    @ApiLogger(apiName="/find/device/for/org/tree")
    @ApiOperation(value = "带单位树型结构的设备列表")
    @ApiImplicitParams(
            {@ApiImplicitParam(name="id", value = "单位id", required=false,dataTypeClass = String.class)})
    @GetMapping("/find/device/for/org/tree")
    @ResponseBody
    public Result findDeviceForOrgTrue(String id) {
        Result result = deviceTreeServiceImpl.findDeviceTree(id);
        if (null != result.getData() && result.getData() instanceof List){
            this.setPosition((List<OrgDeviceBean>)result.getData());
        }
        return result;
    }

    /**
     * 按输入值查询的设备列表
     * @param keyword
     * @param state
     * @return
     */
    @ApiLogger(apiName="/find/device/by/keyword")
    @ApiOperation(value = "输入值查询列表")
    @ApiImplicitParams(
            {@ApiImplicitParam(name="keyword", value = "关键字", required=false,dataTypeClass = String.class)
            ,@ApiImplicitParam(name="state", value = "状态(1在线,-1离线,0全部)", required=false,dataTypeClass = Integer.class)})
    @GetMapping("/find/device/by/keyword")
    @ResponseBody
    public Result findDeviceByKeyword(String keyword,Integer state) {
        Result result = deviceQueryImpl.searchBykeyword(keyword,state);

        if (null != result.getData() && result.getData() instanceof List){
            this.setPosition((List<OrgDeviceBean>)result.getData());
        }
        return result;
    }


    /**
     * 深度查询
     * @param keyword
     * @param state
     * @return
     */
    @ApiLogger(apiName="/find/device/deep")
    @ApiOperation(value = "查询所有的设备数据")
    @ApiImplicitParams(
            {@ApiImplicitParam(name="keyword", value = "关键字", required=false,dataTypeClass = String.class)
                    ,@ApiImplicitParam(name="state", value = "状态(1在线,-1离线,0全部)", required=false,dataTypeClass = Integer.class)})
    @GetMapping("/find/device/deep")
    @ResponseBody
    public Result findDeviceByKeywordDeep(String keyword,Integer state) {

        Result result = deviceQueryImpl.FindAllDeviceDeep(keyword,state);

        if (null != result.getData() && result.getData() instanceof List){
            this.setPosition((List<OrgDeviceBean>)result.getData());
        }
        return result;
    }

    /**
     * 取定位信息 和状态状态信息
     * @param datas
     */
    private void setPosition(List<OrgDeviceBean> datas){
        for(OrgDeviceBean item: datas){
            Double longitude = null;
            Double latitude = null;
            String coordinateSystem="WGS84"; //坐标系 WGS84，GCJ02
            Device device = null;
            if ("chn".equals(item.getType())){
                Object obj = null;
                PositionInfo positionInfo = null;
                if ((obj=item.getArrt().get("deviceCode")) != null){
                    device = deviceService.getFromCache(obj.toString());

                    if ((positionInfo = positionUtil.getCurrentPosition(obj.toString())) != null){
                        longitude = positionInfo.getLongitude();
                        latitude = positionInfo.getLatitude();
                        coordinateSystem = positionInfo.getCoordinateSystem();
                    }else{
                        if (device !=null){
                            //取此设备最后的定位
                            longitude = device.getLongitude();
                            latitude = device.getLatitude();
                            coordinateSystem = device.getCoordinateSystem();
                        }
                    }
                    //设备状态信息
                    item.getArrt().put("batteryInfo",device.getBatteryInfo());
                    item.getArrt().put("storage",device.getStorage());
                    item.getArrt().put("usedMemory",device.getUsedMemory());
                    item.getArrt().put("remainMemory",device.getRemainMemory());
                    item.getArrt().put("recordStatus",device.getRecordStatus());

                }

                if (longitude == null || 0.0==longitude){
                    //取中心点
                    Map<String,Double> point = MapUtil.getCenterPoint();
                    longitude = point.get("longitude").doubleValue();
                    latitude = point.get("latitude").doubleValue();
                }
                if (item.getChildren()!=null && item.getChildren().size()>0){
                    for(OrgDeviceBean child: item.getChildren()){
                        child.setLongitude(longitude);
                        child.setLongitude(latitude);
                        child.setCoordinateSystem(coordinateSystem);
                    }
                }
                item.setLongitude(longitude);
                item.setLatitude(latitude);
                item.setCoordinateSystem(coordinateSystem);

            }else if ("org".equals(item.getType()) || "dev".equals(item.getType())){
                if (item.getChildren()!=null && item.getChildren().size()>0){
                    this.setPosition(item.getChildren());//递归
                }
            }
        }
    }

}
